<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item v-for="(item, index) in breadList" :key="index" :to="{ path: item.path }">{{ item.meta.title
        }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box" style="margin-bottom: 10px">
        <el-input v-model="query.content" placeholder="请输入关键字" class="handle-input mr10" type="text"
          style="max-width: 400px; margin-right: 10px"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">
          搜索
        </el-button>
      </div>
      <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header">
        <el-table-column prop="comId" label="ID" width="55" align="center"></el-table-column>
        <el-table-column prop="username" label="用户名" width="80" align="center"></el-table-column>
        <el-table-column prop="content" label="内容" width="130" align="center">
          <template #default="scope">
            <div v-html="handleHighlight(parseHTML(scope.row.content), query.content)
              "></div>
          </template></el-table-column>
        <el-table-column prop="like" label="点赞数" width="80" align="center"></el-table-column>
        <el-table-column label="发表时间" width="250" align="center">
          <template #default="scope">
            {{ moment(scope.row.createdAt).format("YYYY-MM-DD HH:mm") }}
          </template>
        </el-table-column>
        <el-table-column label="修改时间" width="250" align="center">
          <template #default="scope">
            {{ moment(scope.row.updatedAt).format("YYYY-MM-DD HH:mm") }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-popconfirm title="确定要删除此评论？" confirm-button-text="确定" cancel-button-text="取消"
              @confirm="handleDelete(scope.$index, scope.row)">
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!--   分页   -->
      <div class="pagination">
        <el-pagination v-if="totalCount" v-model:currentPage="query.currentPage" v-model:page-size="query.pageSize"
          layout="prev, pager, next, jumper" :total="totalCount" @current-change="handleCurrentChange" />
      </div>
    </div>
    <el-dialog v-model="dialogVisible" title="评论编辑" width="40%">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" status-icon>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <div style="height: 300px; overflow-y: auto">
            <mavon-editor v-model="ruleForm.content" style="width: 100%" ref="md" />
          </div>
        </el-form-item>
        <el-form-item label="点赞数" prop="like">
          <el-input type="number" max="5" min="1" v-model="ruleForm.like" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(ruleFormRef)">更新</el-button>
          <el-button @click="resetForm(ruleFormRef)">重置表单</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { ref, reactive, watch } from "vue";
import { ElNotification } from "element-plus";
import request from "../../utils/request";
import { useRoute } from "vue-router";
import moment from "moment";
import "mavon-editor/dist/css/index.css";
export default {
  setup() {
    const tableData = ref([]);
    const pageTotal = ref(0);
    const totalCount = ref(0);
    const categoryData = ref([]);
    const traIdColorMap = {};

    //获取分类数据
    const getCategory = () => {
      request
        .request({
          url: "/category/getAllCategory",
          method: "get",
        })
        .then((res) => {
          //获取数据
          res.data.data.forEach((e) => {
            categoryData.value.push(e);
          });
        })
        .catch((e) => {
          console.log(e);
        });
    };
    getCategory();

    const query = reactive({
      content: "",
      currentPage: 1,
      pageSize: 3,
    });

    let breadList = []; // 路由集合
    const route = useRoute();
    const getBreadcrumb = (url) => {
      let matched = url.matched;
      //如果不是首页
      if ("Home" == matched[0].name) {
        matched[0].meta = { title: "系统首页" };
      }
      breadList = matched;
    };
    watch(
      route,
      (newValue, oldValue) => {
        getBreadcrumb(newValue);
      },
      { deep: true, immediate: true }
    );
    let md = ref(null);
    //修改
    const resetForm = (formEl) => {
      if (!formEl) return;
      formEl.resetFields();
    };
    // 修改评论
    const submitForm = async (formEl) => {
      if (!formEl) return;
      await formEl.validate((valid, fields) => {
        if (valid) {
          request
            .request({
              url: "/comment/update",
              method: "patch",
              data: {
                comId: ruleForm.comId,
                username: ruleForm.username,
                content: ruleForm.content,
                like: ruleForm.like,
              },
            })
            .then((res) => {
              if (res.data.code == 200) {
                getData();
                dialogVisible.value = false;

                ElNotification({
                  title: "更新成功",
                  message: "成功更新评论",
                });
              } else {
                ElNotification({
                  title: "更新失败",
                  message: "请联系管理员检查失败原因",
                });
              }
            })
            .catch((e) => {
              ElNotification({
                title: "更新失败",
                message: "请联系管理员检查失败原因",
              });
            });
        } else {
          ElNotification({
            title: "校验失败",
            message: "请重新填写信息",
          });
        }
      });
    };
    const dialogVisible = ref(false);
    const ruleFormRef = ref();
    const ruleForm = reactive({
      comId: "",
      username: "",
      content: "",
      like: "0",
    });
    //修改页面的要求
    const rules = reactive({
      username: [
        {
          required: true,
          message: "请输入用户名",
          trigger: "blur",
        },
      ],
      content: [
        {
          required: true,
          message: "请输入评论内容",
          trigger: "blur",
        },
      ],
      like: [
        {
          required: false,
          message: "请输入点赞数",
          trigger: "blur",
        },
      ],
    });
    //修改操作
    const handleEdit = (index, row) => {
      dialogVisible.value = true;
      ruleForm.comId = row.comId;
      ruleForm.username = row.username;
      ruleForm.content = row.content;
      ruleForm.like = row.like;
    };

    //删除操作
    const handleDelete = (index, row) => {
      request
        .request({
          url: "/comment/delete",
          method: "delete",
          params: {
            comId: row.comId,
          },
        })
        .then((res) => {
          if (res.data.msg == "success") {
            getData();
            ElNotification({
              title: "删除成功",
              message: "成功删除用户评论信息",
            });
          } else {
            ElNotification({
              title: "删除失败",
              message: "请联系管理员检查失败原因",
            });
          }
        })
        .catch((e) => {
          ElNotification({
            title: "删除失败",
            message: "请联系管理员检查失败原因",
          });
        });
    };

    const getData = () => {
      request
        .request({
          url: "/comment/getAllCommentsByPage",
          method: "get",
          params: {
            content: query.content,
            currentPage: query.currentPage,
            pageSize: query.pageSize,
          },
        })
        .then((res) => {
          //获取当前页的数据
          tableData.value = res.data.data.rows;
          //获取总记录数
          totalCount.value = res.data.data.count;
        })
        .catch((e) => {
          console.log(e);
        });
    };

    const getRandomColor = () => {
      const colors = ["warning", "danger", "primary", "success", "info"]; // 定义颜色选项
      const randomIndex = Math.floor(Math.random() * colors.length); // 随机选择颜色
      return colors[randomIndex]; // 返回对应颜色的type值
    };

    const getTraIdColor = (traId) => {
      if (!traIdColorMap[traId]) {
        // 若字典中不存在对应的颜色，则生成一个新颜色并保存到字典中
        traIdColorMap[traId] = getRandomColor();
      }
      return traIdColorMap[traId]; // 返回对应的颜色
    };
    const parseHTML = (content) => {
      const parser = new DOMParser();
      const doc = parser.parseFromString(content, "text/html");
      return doc.body.innerHTML;
    };
    //高亮效果
    const handleHighlight = (content, keyword) => {
      if (!keyword) {
        return content;
      }
      const regex = new RegExp(keyword, "gi");
      return content.replace(
        regex,
        '<span style="background-color: yellow;">$&</span>'
      );
    };
    getData();

    const handleSearch = () => {
      getData();
    };
    // 分页导航
    const handleCurrentChange = (val) => {
      query.currentPage = val;
      getData();
      // console.log(val);
    };

    return {
      ruleFormRef,
      query,
      pageTotal,
      tableData,
      dialogVisible,
      rules,
      totalCount,
      ruleForm,
      breadList,
      route,
      categoryData,
      moment,
      resetForm,
      submitForm,
      getData,
      handleSearch,
      handleDelete,
      handleEdit,
      handleCurrentChange,
      handleHighlight,
      parseHTML,
      getRandomColor,
      getCategory,
      traIdColorMap,
      getTraIdColor,
    };
  },
};
</script>

<style scoped></style>
